package view;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import server.Log;
import server.RulesTableType;


/**
 * Frame is responsible for window with all filter options.
 */
public class LoggerFilterFrame extends JFrame
{ 
	private static final long serialVersionUID = 36785838378185037L;
	
	/* Current shown window */
	public static LoggerFilterFrame currentFilterFrame = null;
	public static FilterType currentType = FilterType.ALL; //TODO
	
	/* Directions */
	public static String[] dirStrings = {"",RulesTableType.IN.toString(),RulesTableType.OUT.toString()};
	/* Filters */
	public static FilterType[] filterStrings = {FilterType.ALL,
												FilterType.IP,
												FilterType.PROTOCOL};
	public static JRadioButton[] filterButtons = new JRadioButton[filterStrings.length];
	
	/* History depth */
	private static JTextField numOfDaysField  = null;
	/* Textbox for protocol */
	private static JTextField protocolTextField = null;
	/* Textbox for port */
	private static JTextField portTextField = null;
	/* Textbox for IP */
	private static JTextField ipTextField = null;
	/* Field to choose direction */
	private static JComboBox directionField = null;
	
	/* Filter parameter */
	private JPanel generalPanel = null; // Panel for all filters and parameters

	/* Panels for parameters */
	private JPanel protocolPanel = null;
	private JPanel ipPanel = null;
	
	/* last opened panel for parameters */
	private JPanel lastOpenedPanel = null;

	/**
	 * C'tor
	 * Define the frame.
	 */
	public LoggerFilterFrame()
	{
		/* Window's characteristics */
		setTitle("Filter Options");
	    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setLayout(new BorderLayout());
		setSize(400, 150);
		
		/* Panel for history options */
		JPanel historyPanel = new JPanel(new BorderLayout());
		
		JLabel historyLabel = new JLabel("Logger hitory (in days):");
		historyPanel.add(historyLabel, BorderLayout.NORTH);

		numOfDaysField  = new JTextField();
		if (Settings.historyDepth != -1 )
		{
			numOfDaysField.setText(Integer.toString(Settings.historyDepth));
		}
		historyPanel.add(numOfDaysField, BorderLayout.CENTER);		
		add(historyPanel, BorderLayout.NORTH);
		
		/* Panel for filter options and parameters */
		generalPanel = new JPanel(new GridLayout(1,2));
		
		/* Panel for filter options */
		JPanel filter = new JPanel(new GridLayout(4,1));
		JLabel filterLabel = new JLabel("Filter options:");
		filter.add(filterLabel);
		
		/* Radio buttons */
		ButtonGroup filterTypeGroup = new ButtonGroup();
		
		for(int i = 0; i < filterStrings.length; i++)
		{
			filterButtons[i] = new JRadioButton();
			filterButtons[i].setText(filterStrings[i].toString());
			filterTypeGroup.add(filterButtons[i]);
			filter.add(filterButtons[i]);
			/* New options are shown for each radio buttons */
			filterButtons[i].addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e)
				{
					for(int i = 0; i < filterButtons.length; i++)
					{
						if(filterButtons[i].isSelected())
						{
							/* Delete last panel */
							if(lastOpenedPanel != null)
							{
								lastOpenedPanel.setVisible(false);
								generalPanel.remove(lastOpenedPanel);
							}
							
							/* Add new panel and remember options */
							switch(filterStrings[i])
							{
							case PROTOCOL:
								generalPanel.add(protocolPanel);
								lastOpenedPanel = protocolPanel;
								protocolPanel.setVisible(true);
								currentType = FilterType.PROTOCOL;
								break;
							case IP:
								generalPanel.add(ipPanel);
								lastOpenedPanel = ipPanel;
								ipPanel.setVisible(true);
								currentType = FilterType.IP;
								break;
							case ALL:
								currentType = FilterType.ALL;
								lastOpenedPanel = null;
								break;
							}
						}
					}/*for(int i = 0; i < filterButtons.length; i++)*/
					currentFilterFrame.setVisible(true);
				}
			});
		}
		filterButtons[0].setSelected(true);
		generalPanel.add(filter);
		
		add(generalPanel, BorderLayout.CENTER);

		/* Create panels for the view */
		createParametersPanels();
		
		/* Standart buttons */
	    addStandartButtons();
	    
	    /* Store the current open window */
	    currentFilterFrame = this;
	  }


	private void createParametersPanels()
	{		
		/* Parameters for protocol */
		protocolPanel = new JPanel(new GridLayout(3,2));	

		JLabel protocolLabel = new JLabel("Protocol:");
		protocolPanel.add(protocolLabel);
		protocolTextField = new JTextField(Settings.filterProtocol);
		protocolPanel.add(protocolTextField);
		
		/* Parameters for IP */
		ipPanel = new JPanel(new GridLayout(3,2));	

		JLabel ipLabel = new JLabel("IP:");
		ipPanel.add(ipLabel);
		ipTextField = new JTextField();
		ipPanel.add(ipTextField);
		JLabel portLabel = new JLabel("Port:");
		ipPanel.add(portLabel);
		portTextField = new JTextField();
		ipPanel.add(portTextField);
		JLabel dirLabel = new JLabel("Direction:");
		ipPanel.add(dirLabel);
		directionField = new JComboBox(dirStrings);
		ipPanel.add(directionField);
	}
	
	/**
	 * This method adds standart help/finish/cancel buttons to the current frame
	 */
	private void addStandartButtons() 
	{
		Box tableBox = Box.createHorizontalBox();
		
		JButton finish = new JButton("Finish");
		finish.setToolTipText("Close and save changes");
		JButton cancel = new JButton("Cancel");
		cancel.setToolTipText("Close without saving changes");		

		tableBox.add(finish);
		tableBox.add(cancel);
		
	    add(tableBox, BorderLayout.SOUTH);
	    
		/*Finish button listener - closes the frame and stores the changes */
		finish.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) 
			{
				Settings.historyDepth = -1;
				Settings.filterProtocol = null;
				Settings.filterIP = null;
				Settings.filterPort  = null;
				Settings.filterDir = null;
				
				/* Add new panel and remember options */
				switch(currentType)
				{
				case PROTOCOL:
					String protocol = protocolTextField.getText();
					if (!protocol.equals(""))
					{
						Settings.filterProtocol = protocol;
					}
					Settings.currentFilterType = FilterType.PROTOCOL;
					break;
				case IP:
					/*get IP*/
					String ip = ipTextField.getText();
					if (!ip.equals(""))
					{
						Settings.filterIP = ip;
					}
					
					/*get Port*/
					String port = portTextField.getText();
					if(!port.equals(""))
					{
						try 
						{
							Settings.filterPort = Integer.parseInt(port);
						} 
						catch (NumberFormatException e)
						{
							ErrorFrame.AddError("Illegal port number is entered (need natural number)", 
												 currentFilterFrame);
							return;
						}						
					}

					String dir = (String) directionField.getSelectedItem();
					if (dir.equals(RulesTableType.IN.toString()))
					{
						Settings.filterDir = Log.directOpt.IN;
					}
					else if(dir.equals(RulesTableType.OUT.toString()))
					{
						Settings.filterDir = Log.directOpt.OUT;
					}					
					Settings.currentFilterType = FilterType.IP;
					break;
				case ALL:
					Settings.currentFilterType = FilterType.ALL;
					break;
				}
				
				try 
				{
					String days = numOfDaysField.getText();
					if (days == null || days.equals(""))
					{
						Settings.historyDepth = -1;
					}
					else
					{ 
						Settings.historyDepth =  Integer.parseInt( numOfDaysField.getText());
					}
				}
				catch (NumberFormatException e)
				{
					ErrorFrame.AddError("Illegal days number is entered (need natural number)", 
						 currentFilterFrame);
					return;	
				}
				
				LoggerTable.currentLoggerTable.build();
				LoggerGlobalTable.currentLoggerGlobalTable.build();
				currentFilterFrame.dispose();
			}	  
		});
		  
		/*Cancel button listener - closes the frame*/		
		cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) 
			{
				currentFilterFrame.dispose();		
			}	  
		});	
	}
		
}
